package dao

import (
	"Wechat/Tools"
	"Wechat/domain"
)

// SourceMapper 建立一个sourcemapper用于调用函数
type SourceMapper string

// 获取数据库连接
var sourceDB = Tools.GetDB()

// AddSource 添加资源
func (s SourceMapper) AddSource(source domain.Source) int64 {
	result := sourceDB.Create(&source)
	Tools.CherrError(result.Error, "Insert source ERROR!")
	return result.RowsAffected
}

// GetSourceCategory 根据类别获取资源
func (s SourceMapper) GetSourceCategory(category string, id int) []domain.Source {
	var sourceArr []domain.Source
	result := sourceDB.Limit(10).Order("sourceTime DESC").Where("sourceID > ? AND sourceCategory = ?", id, category).Find(&sourceArr)
	Tools.CherrError(result.Error, "Get source bt category ERROR!")
	return sourceArr
}

// GetSource 获取全部资源
func (s SourceMapper) GetSource(id int) []domain.Source {
	var sourceArr []domain.Source
	result := sourceDB.Limit(10).Order("sourceTime DESC").Where("sourceID > ?", id).Find(&sourceArr)
	Tools.CherrError(result.Error, "Get source ERROR!")
	return sourceArr
}

// GetDetail 获取资源详情
func (s SourceMapper) GetDetail(id int) domain.Source {
	var source domain.Source
	result := sourceDB.Where("sourceID = ?", id).Find(&source)
	Tools.CherrError(result.Error, "Get source detail ERROR!")
	return source
}

// 获取最新的资源
func (s SourceMapper) GetNewSource() domain.Source {
	var source domain.Source
	result := sourceDB.Limit(1).Order("sourceTime DESC").Find(&source)
	Tools.CherrError(result.Error, "Get new source ERROR!")
	return source
}
